package com.silong.swing.myWindows;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by 龙哥 on 2022-01-17 15:38
 * Silong Software.
 * 直接在窗体类上实现监听
 */

public class MyFrameImplActionListener extends JFrame implements ActionListener {

    private JButton button1;
    private JButton button2;
    int count1 = 0; //计数器
    int count2 = 0; //按钮2计数器
    public MyFrameImplActionListener(){
        init();
    }

    private void init(){

        button1 = new JButton("按钮一");
        button2 = new JButton("按钮二");

        Container window = this.getContentPane();
        this.setSize(800, 600);
        this.setLocationRelativeTo(null); //距中
        this.setTitle("自定义控件大小位置");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //退出窗口关闭程序

        //设置布局为空，优点:摆放灵活，缺点：代码量大，自适应能力差。
        this.setLayout(null);

        //自定义按钮的位置 ，大小
        button1.setLocation(100,50); //设置按钮位置
        button1.setSize(200,50); //设置按钮大小
        button1.addActionListener(this);  //添加监听事件
        button2.setBounds(400, 50, 200, 50); //一次性设置位置与大小
        button2.addActionListener(this);

        window.add(button1);
        window.add(button2);
    }

    /**
     * 监听事件
     * @param e
     */
    @Override
    public void actionPerformed(ActionEvent e) {

        if(e.getSource() == button1){
            ++count1;
            button2.setText("buttun1被点击" + count1 + "次");
        }else{
            ++count2;
            button2.setText("buttun2被点击" + count2 + "次");
        }
    }
}
